package com.lzb.browser.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

import com.lzb.browser.BaseAc;
import com.lzb.browser.Content;
import com.lzb.browser.HomeActivity;
import com.lzb.browser.R;
import com.lzb.browser.basic.utils.SPUtil;
import com.lzb.browser.databinding.ActivityCalculatorBinding;

public class CalculatorActivity extends BaseAc<ActivityCalculatorBinding> {

    private Handler longPressHandler;
    private Runnable longPressRunnable;
    private boolean isLongPressing = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_calculator;
    }

    @Override
    protected void initView() {
        setupEqualButtonLongPressListener();
    }

    @Override
    protected void initData() {

    }

    /**
     * 设置等于按钮长按监听器
     */
    private void setupEqualButtonLongPressListener() {
        longPressHandler = new Handler();
        
        // 为等于按钮设置触摸监听器
        mDataBinding.tvEqual.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                handleEqualButtonTouch(event);
                return false; // 返回false让按钮保持原有的点击功能
            }
        });
    }

    /**
     * 处理等于按钮的触摸事件
     */
    private void handleEqualButtonTouch(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startLongPress();
                break;
                
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                cancelLongPress();
                break;
        }
    }

    /**
     * 开始长按检测
     */
    private void startLongPress() {
        isLongPressing = true;
        
        longPressRunnable = new Runnable() {
            @Override
            public void run() {
                if (isLongPressing) {
                    onEqualLongPressDetected();
                }
            }
        };
        longPressHandler.postDelayed(longPressRunnable, 2000); // 2秒长按
    }

    /**
     * 取消长按检测
     */
    private void cancelLongPress() {
        isLongPressing = false;
        if (longPressRunnable != null) {
            longPressHandler.removeCallbacks(longPressRunnable);
        }
    }

    /**
     * 等于按钮长按事件触发
     */
    private void onEqualLongPressDetected() {
        // 等于按钮长按2秒触发事件
        boolean isHave = SPUtil.getBoolean(getApplicationContext(), Content.isHavePassword, false);
        if (isHave){
            startActivity(InputPatternPswActivity.class);
            finish();
        }else {
            startActivity(HomeActivity.class);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelLongPress();
        if (longPressHandler != null) {
            longPressHandler.removeCallbacksAndMessages(null);
        }
    }
}